import { onMounted, onUnmounted } from "vue"

export const useWindowSize = ()=>{
    let timer : ReturnType<typeof setTimeout> | null = null

    type ResizeCallBack = (num : Number)=> void
    let resizeCallBack : (ResizeCallBack | null) = null

    const reSizeEvent = (cb : ResizeCallBack)=>{
        resizeCallBack = cb
    }
    
    onMounted(()=>{
        const throttl = (cb : ()=> void)=>{
            if(timer){
                return
            }
            timer = setTimeout(()=>{
                clearTimeout(timer!)
                timer = null
                cb()
            },300)
        }
        window.addEventListener("resize", () => {
            // 获取窗口宽度
            throttl(()=>{
                const windowWidth = window.innerWidth;
                let normalFontSize = 17
                let maxScreenWidth = 1224
                let scale = (windowWidth / maxScreenWidth)
                document.documentElement.style.fontSize = (normalFontSize * scale) + 'px'
                // console.log('windowWidth:' + windowWidth)
                resizeCallBack && resizeCallBack(scale)
            })
        })
    })

    onUnmounted(()=>{
        timer && clearTimeout(timer)
    })

    return { reSizeEvent }
}
